import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-pdf-preview',
  templateUrl: './pdf-preview.component.html',
  styleUrls: ['./pdf-preview.component.scss']
})
export class PdfPreviewComponent implements OnInit, OnChanges {

  @Input() showType = false // 是否支持两次一样的 url 
  constructor() { }
  

  ngOnInit(): void {
  }
  ngOnChanges(changes: SimpleChanges): void {
    console.log(changes)
    if(changes['pdfId']?.currentValue){
      this.nzSpinning = true
      this.nzVisible = true
      setTimeout(() => {
        this.nzVisibleChange.emit(this.nzVisible)
      }, 0);
      this._pdfPreview(this.pdfId)
      return
    }
    if(changes['pdfUrl']?.currentValue){
      this.nzSpinning = true
      this.nzVisible = true
      setTimeout(() => {
        this.nzVisibleChange.emit(this.nzVisible)
      }, 0);
      this._pdfPreview(this.pdfUrl, 1)
      return
    }

    if(changes['nzVisible']?.currentValue && this.showType){
      if(this.pdfId){
        this._pdfPreview(this.pdfId)
        return
      }
      if(this.pdfUrl){
        this._pdfPreview(this.pdfUrl, 1)
        return
      }
    }
  }

  @Input() nzVisible = false
  @Output() nzVisibleChange = new EventEmitter()
  @Input() pdfId = ''
  @Input() pdfUrl = ''

  @Input() title: any = null
  @Input() cancelBtnText = '取消'
  @Input() okBtnText = '确定'

  @Input() btnLoading = false

  @Output() onOkBtn = new EventEmitter()
  @Output() onCancelBtn = new EventEmitter()

  nzSpinning = false
  modalHandleCancel(){
    this.nzVisible = false
    this.nzVisibleChange.emit(this.nzVisible)
    this.onCancelBtn.emit()
  }
  modalHandleOk(){
    this.onOkBtn.emit()
  }

  _pdfPreview(url: string, type = 0){
    let f = document.createElement('iframe');
    if(type === 0){
      f.src = 'assets/js/pdfjs/web/viewer.html?file=' + environment.downloadUrl + url;
    }
    if(type === 1){
      f.src = 'assets/js/pdfjs/web/viewer.html?file=' + url;
    }
    f.width = '752';
    f.height = '420';

    setTimeout(()=>{
      (document.getElementById('pdfpreview') as any).appendChild(f);
      
      this.nzSpinning = false;
    }, 0)
  }

}
